﻿using System.Collections.Generic;
using System.Linq;
using Nb.Common.Ioc;
using Nb.Licenses.Libs.Hardwares;
using Nb.Licenses.Libs.MachineCodes;
using Nb.Licenses.Libs.Providers;

namespace Nb.Licenses.Libs
{
    internal class NbLicensesFactory : ILicenseFactory
    {
        public IMachineInfoService GetMachineInfoService()
        {
            return new MachineInfoService();
        }

        public IMachineCodeService GetMachineCodeService()
        {
            return new MachineCodeService();
        }

        public IMachineCodeValidateService GetMachineCodeValidateService()
        {
            return new MachineCodeService();
        }
    }

    /// <summary>
    /// 可以多个Provider中读取，按优先级提供，比如
    /// query, cookie, config, services...
    /// </summary>
    public class LicenseManager
    {
        private static IList<ILicenseFactoryProvider> _defaultProviders = new List<ILicenseFactoryProvider>()
        {
            new DefaultLicenseFactoryProvider()
        };

        private static bool needSearchAllProviders = true;

        public static ILicenseFactory GetFactory()
        {
            var providers = new List<ILicenseFactoryProvider>();
            providers.AddRange(_defaultProviders);

            if (needSearchAllProviders)
            {
                var moreProviders = CoreServiceProvider.Current.GetAllInstances<ILicenseFactoryProvider>()
                    .Where(p =>
                        p.GetType() != typeof (DefaultLicenseFactoryProvider))
                    .ToList();

                //Count > 0，意味着定义了其他的Provider
                //否则，下次没有机会在执行此代码块
                needSearchAllProviders = moreProviders.Count > 0;
                providers.AddRange(moreProviders);
            }

            //值越大，越靠前
            var licenseFactoryProvider = providers.OrderByDescending(x => x.Priority).First();
            var licenseFactory = licenseFactoryProvider.GetFactory();
            return licenseFactory;
        }
    }
}